import { debounce } from "../../utils/debounce"

const saveState = () => {
  localStorage.setItem('historySearch', JSON.stringify(state));
}

const debounceFunc = debounce(saveState,1000)

const state = localStorage.getItem('historySearch') == null ? {
  historySearch: []
} : JSON.parse(localStorage.getItem('historySearch'))

const getters = {
  historySearch: state => state.historySearch,
}

const mutations = {
  SET_SEARCH_HISTORY(state,val){
    var obj = JSON.parse(val);

    var tempArr = state.historySearch.filter(item => item.name == obj.name);

    if(tempArr.length == 0){

      if(state.historySearch.length >= 10){
        state.historySearch.splice(0,1)
      }

      state.historySearch.push(obj);
    }
    
    debounceFunc.apply(null,[]);
  }
}

const actions = {
  addSearchRecord({commit} , val){
    return new Promise((resolve, reject) => {
      commit('SET_SEARCH_HISTORY',val);
      resolve();
    })
    
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}